import tool from '@/utils/tools';
import Dialog from 'tdesign-miniprogram/dialog/index';
import Message from 'tdesign-miniprogram/message/index';

import intervalStore from '@/store/interval';
import { createStoreBindings } from '@/miniprogram_npm/mobx-miniprogram-bindings/index';

import { login, register, getValidateCode, checkValidateCode } from '@/service/api/user';
import tools from '@/utils/tools';

const messageDefaultConfig = (content) => {
    return {
        offset: [90, 32],
        content: content,
        duration: 2000
    };
};

const accountPattern = /^[1-9]\d{8}$/;
const passwordPattern = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;
const emailPattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/;

let validateChecked = false;

Page({
    data: {
        loginModel: 0,
        loginPageClass: {
            login: ':active',
            register: ''
        },
        loginAccount: '',
        loginPassword: '',
        registerAccount: '',
        registerPassword: '',
        registerEmail: '',
        validateCode: ''
    },

    onLoad() {
        this.storeBindings = createStoreBindings(this, {
            store: intervalStore,
            fields: ['currentSecond'],
            actions: ['setNewInterval']
        });
    },

    onUnload() {
        this.storeBindings.destroyStoreBindings();
    },

    changeLoginModel() {
        this.setData({
            loginAccount: '',
            loginPassword: '',
            registerAccount: '',
            registerPassword: '',
            registerEmail: '',
            validateCode: ''
        });
        this.data.loginModel == 0 ? this.setData({ loginModel: 1 }) : this.setData({ loginModel: 0 });
    },

    async loginValidate() {
        if (!accountPattern.test(this.data.loginAccount) && !emailPattern.test(this.data.loginAccount)) {
            Message.warning(messageDefaultConfig('请输入正确格式的账号或邮箱地址'));
            return;
        }
        if (!passwordPattern.test(this.data.loginPassword)) {
            Message.warning(messageDefaultConfig('请输入正确格式的密码'));
            return;
        }
        try {
            let loginData = {
                account: this.data.loginAccount,
                password: this.data.loginPassword
            };
            await login(loginData);
            wx.switchTab({
                url: '/pages/index/index'
            });
        } catch (err) {
            Message.error(messageDefaultConfig(err.message));
        }
    },

    async registerValidate() {
        // 账号正确校验
        if (!accountPattern.test(this.data.registerAccount)) {
            Message.error(messageDefaultConfig('请输入9位数字账号且不能为0开头'));
            return;
        }
        // 密码正确校验
        if (!passwordPattern.test(this.data.registerPassword)) {
            Message.error(messageDefaultConfig('密码长度至少8位，使用字母数字组合'));
            return;
        }
        // 邮箱格式校验
        if (!emailPattern.test(this.data.registerEmail)) {
            Message.error(messageDefaultConfig('请输入正确格式的邮箱地址'));
            return;
        }
        if (!validateChecked) {
            Message.error(messageDefaultConfig('请完成邮箱校验'));
            return;
        }
        if (!/\d{4}/.test(this.data.validateCode)) {
            Message.error(messageDefaultConfig('请输入4位数字验证码'));
            return;
        }
        try {
            await checkValidateCode(this.data.registerEmail, this.data.validateCode);
            // 生成用户信息
            const data = {
                account: this.data.registerAccount,
                userName: `用户${tools.getRandomNum(100000, 999999)}`,
                password: this.data.registerPassword,
                email: this.data.registerEmail,
                frozen: 0,
                role: 0
            };
			await register(data);
            Dialog.confirm({
                title: '注册成功',
                closeOnOverlayClick: false,
                content: '账号注册成功，请返回登陆',
                confirmBtn: '确定'
            }).then(() => {
                wx.reLaunch({
                    url: '/pages/login/login'
                });
            });
        } catch (err) {
            Message.error(messageDefaultConfig(err.message));
        }
    },

    validate: tool.throttle(function () {
        this.data.loginModel == 0 ? this.loginValidate() : this.registerValidate();
    }, 1500),

    // 获取邮箱验证码
    async getValidateCode() {
        if (!emailPattern.test(this.data.registerEmail)) {
            Message.error(messageDefaultConfig('请输入正确格式的邮箱地址'));
            return;
        }
        if (this.data.currentSecond !== 0) {
            return;
        }
        try {
            // 发送短信验证码
            await getValidateCode(this.data.registerEmail);
            this.setNewInterval(60);
            validateChecked = true;
            Message.success(messageDefaultConfig('验证码已发送，注意查看邮箱'));
        } catch (err) {
            Message.error(messageDefaultConfig(err.message));
        }
    },

    jumpToForget() {
        intervalStore.clearInterval();
        wx.navigateTo({
            url: '/pages/forget/index'
        });
    }
});
